<template>
  <div>
      <!-- 顶部栏 -->
      <van-nav-bar title="搜索页" left-arrow @click-left="$router.back()"/>
      <!-- 搜索框 -->
      <van-search
      v-model="value"
      show-action
      shape="round"
      placeholder="请输入搜索关键词"
      autofocus
      @search="onSearch"
      @input="onInput"
      >
      <template #action>
          <div @click="onSearch">搜索</div>
      </template>
      </van-search>
      <!-- 搜索列表 -->
      <van-cell-group>
          <van-cell v-for="(item,index) in showList"
          :key="index"
          icon="search"
          @click="$router.push({path:'/searchResult',query:{q:suggestionList[index]}})">
          <template #title>
              <span class="custom-title" v-html="item"></span>
          </template>
          </van-cell>
          
      </van-cell-group>
  </div>
</template>

<script>
import {getSuggestion} from './home'
export default {
   name:"search",
   data() {
       return {
           value:'',
           suggestionList:[]
       }
   },
   methods: {
    //    搜索事件:输入框回车+点击右侧搜索按钮
    onSearch(){
        console.log('搜索'+ this.value);
        // 跳转搜索结果页并传参
        this.$router.push({path:'/searchResult',query:{q:this.value}})
    },
    // 输入事件 输入框内容变化
     onInput(){
        //  防抖第一步先清除上一次定时器 以最后一次为准
        clearTimeout(this.timeID)
        // 第二步开启防抖定时器
        this.timeID = setTimeout(async()=>{
            console.log('输入'+this.value);
      
        // 非空判断
        if(this.value == ''){
            this.suggestionList = []
            return
        }
        // 获取推荐词列表
        let res = await getSuggestion(this.value)
        console.log(res);
        // 绑定数据
      
      this.suggestionList = res.data.data.options
        },500)
    }
    
   },
   computed:{
    showList(){
    //map遍历数组 根据某种映射规则生成一个新的数组
        return this.suggestionList.map(value=>{
           let reg = new RegExp(this.value,'ig')
           return value.replace(
               reg,
               match => `<span style="color:red">${match}</span>`
           )
        })
    }
   }
}
</script>

<style>

</style>